import collections
from typing import Dict


class Solution:
    def balancedString(self, s: str) -> int:
        cntMap = collections.Counter(s)
        targetCount = len(s)//4

        moreMap = {}
        subLen = 0
        for c in ['Q', 'W', 'E', 'R']:
            if cntMap[c] > targetCount:
                moreMap[c] = cntMap[c]-targetCount
                subLen += cntMap[c]-targetCount

        while subLen < len(s):
            for i in range((len(s)-subLen+1)):
                if self.__cal_count(s[i:subLen+i], moreMap):
                    return subLen
            subLen += 1

        return 0

    def __cal_count(self, sub: str, countMap: Dict[str, int]) -> bool:
        cntMap = collections.Counter(sub)
        for c in countMap.keys():
            if countMap[c] > cntMap.get(c, 0):
                return False

        return True


# print(Solution().balancedString("WQWRQQQW"))
print(Solution().balancedString("EQWEEEWERRWERQQQWWQEQWEEWQRWQWWWQWRWEWERWQEWWQWWQRRQWQERWWQRERRRRRWQEQRERRWRREEEERRWERQRQEWREQREWWEWRRRERWRRWEQWQQRRWQEREEEERWQWEWQEWRWREWQEREQWQEQWRQQQWRWWRWERWQWWQQREWREEWRWWQRWQRWWQWWREWWWEWQRWRRWQEWRRRWWQRRQREQRWRRQWREQWEQRWQRWQRWERRREEREEQQEREREWQQWRWEWEQQRWEWEQWEEQEEERWWWEQRRRWRQWWQQEQRWRWRWEQRRQRQRQWWWEQWERWEQRWQRERWQQQWWWQWRWEREWRQWQWERRQQWRQWRWQQQEEQREQWRWWEQRWWWEEERQWQWEWRQQRWQWEQQEWEWRQWWERERQREWWEEREQRRWQRRRWQEEWEWQEEEQRQQEWREQWQWRRWREQQQEEEWWRQEEEWQQEQEQWWREEWRQQQRQQEERQQQEEQWERRQEEQQRQQQWWEQEEQWRQWEQWEEQQEEQQEERQEEWQEEEWQRERRERQRQQQQWRQRRQQWQEEWRRQEWQWREWERWQRQQWEEERREQEEQWQQRWERWRWEEQWEREREWRWREEWRRRQEQQERRRERQRQWRWWREQQWWEQQWQWRRWEQRWEQQEQWWWQWWEWWEEEWEWRQWQWWQQQQEWRQEQWWRWWEQRRRWREREWRQQERQRQEQ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